package com.jinlejia.erp.ui.customer;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.AppointmentVisitAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentAppointmentBinding;
import com.jinlejia.erp.ui.home.AppVisitDetailsActivity;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.ui.mine.adapter.TimeDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 约看（客源Fragment）.
 */

public class AppointmentFragment extends Fragment implements OnDateSetListener, YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private View view;

    private String headers[] = {"约看状态", "约看日期"};
    private String state[] = {"约看状态", "未完成", "已完成", "已过期", "已取消"};
    private String time[] = {"最早日期", "最晚日期"};

    private GirdDropDownAdapter stateAdapter;
    private TimeDropDownAdapter timeAdapter;
    private AppointmentVisitAdapter adapter;

    private List<View> popupViews = new ArrayList<>();

    private ListView stateView;
    private ListView timeView;

    public String startTime = "";
    public String endTime = "";

    private InputMethodManager imm;
    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private String csCode;
    private String types;
    private String sex;

    public static AppointmentFragment newInstance(String code, String type ,String sex) {
        AppointmentFragment fragment = new AppointmentFragment();
        Bundle args = new Bundle();
        args.putString("code", code);
        args.putString("type", type);
        args.putString("sex", sex);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            csCode = getArguments().getString("code");
            types = getArguments().getString("type");
            sex = getArguments().getString("sex");
            jsonObject.put("csCode", csCode);
            if (types.equals("rent")) {
                jsonObject.put("type", "0");
            } else {
                jsonObject.put("type", "1");
            }

        }
    }

    @Override
    public void onStart() {
        super.onStart();
        getData();
    }
    private FragmentAppointmentBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_appointment, null);
            imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            binding = DataBindingUtil.bind(view);
            initView();
            initEvent();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        return view;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        binding.include.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.include.refreshLayout.setOnRefreshListener(this);
        //init state menu
        stateView = new ListView(getActivity());
        stateAdapter = new GirdDropDownAdapter(getActivity(), Arrays.asList(state));
        stateView.setAdapter(stateAdapter);

        stateView.setOnItemClickListener((adapterView, view, i, l) -> {
            stateAdapter.setCheckItem(i);
            binding.include.dropDownMenu.setTabText(i == 0 ? headers[0] : state[i]);
            switch (i) {
                case 0:
                    jsonObject.remove("state");
                    break;
                case 1:
                    jsonObject.put("state", 0);
                    break;
                case 2:
                    jsonObject.put("state", 1);
                    break;
                case 3:
                    jsonObject.put("state", 3);
                    break;
                case 4:
                    jsonObject.put("state", 2);
                    break;
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });

        //init time menu
        final View priceAreaFooter = getActivity().getLayoutInflater().inflate(R.layout.time_menu_footer, null);
        timeView = new ListView(getActivity());
        timeAdapter = new TimeDropDownAdapter(getActivity(), Arrays.asList(time));
        timeView.addFooterView(priceAreaFooter);
        timeView.setAdapter(timeAdapter);

        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm1 = priceAreaFooter.findViewById( R.id.bt_confirm);

        //点击重置
        cancel.setOnClickListener(v -> {
            timeAdapter.startTime = "";
            timeAdapter.endTime = "";
            startTime = "";
            endTime = "";
            binding.include.dropDownMenu.setTabText("约看日期");
            timeAdapter.notifyDataSetChanged();
        });

        //确定按钮
        confirm1.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
                jsonObject.put("appointmentStartTime", startTime);
                jsonObject.put("appointmentEndTime", endTime);
            } else {
                jsonObject.remove("appointmentStartTime");
                jsonObject.remove("appointmentEndTime");
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });

        //init popupViews
        popupViews.add(stateView);
        popupViews.add(timeView);

        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.include.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.include.contractRecyclerView.setHasFixedSize(true);
        binding.include.contractRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.include.contractRecyclerView.enableAutoLoadMore(this);

        adapter = new AppointmentVisitAdapter(dataList,sex);
        binding.include.contractRecyclerView.setAdapter(adapter);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {

        timeView.setOnItemClickListener((adapterView, view, i, l) -> {
            show(time[i]);
            timeAdapter.setCheckItem(i);
//                dropDownMenu.setTabText(startTime + "—" + endTime);
        });
        adapter.setOnItemClickListener((view, o) -> {
            Intent intent = new Intent(getActivity(), AppVisitDetailsActivity.class);
            intent.putExtra("appointmentCode", ((Map<String, Object>) o).get("appointmentCode").toString());
            intent.putExtra("sex",sex);
            intent.putExtra("customerType",types);
            startActivity(intent);
        });
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = DateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = DateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.include.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.include.dropDownMenu.setTabText(startTime + endTime);
        }
    }

    public void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getActivity().getSupportFragmentManager(), "year_month_day");
    }

    /**
     * 获取数据
     */
    public void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 10);
        jsonObject.put("pageIndex", page);
        jsonObject.put("csCode", csCode);
        OkHttpUtils
                .postString()
                .url(ApiConfig.CUSTOMER_APPOINTMENT_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(response.get("data").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            if (page > 1)
                            page--;
                        } else if (response.get("code").toString().equals("501")) {
                            adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                        if (binding.include.refreshLayout.isRefreshing()) {
                            binding.include.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        }else if( adapter.getData().size() > 10 ){
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }
}
